// 防重复注入机制
if (!window.GLOBAL_PARTICLE_EFFECT) {
    window.GLOBAL_PARTICLE_EFFECT = (function() {
        // =============== 配置参数 ================
        const CONFIG = {
            PARTICLE_COUNT: 80,          // 粒子数量
            LINE_MAX_DISTANCE: 160,      // 连线最大距离(像素)
            BASE_SPEED: 0.6,            // 粒子基础速度
            MOUSE_INFLUENCE: 0.25,       // 鼠标影响系数
            FPS: 60,                     // 帧率限制
            Z_INDEX: 99998,              // 画布层级
            OPACITY: 0.7                 // 画布透明度
        };

        // =============== 核心逻辑 ================
        let canvas, ctx;
        let particles = [];
        let mouse = { x: null, y: null };
        let animationFrameId;
        let width, height;

        // HSL转RGB
        function hslToRgb(h, s, l) {
            h = (h % 360 + 360) % 360 / 360;
            s = Math.min(100, Math.max(0, s)) / 100;
            l = Math.min(100, Math.max(0, l)) / 100;

            let r, g, b;
            if (s === 0) {
                r = g = b = l;
            } else {
                const hue2rgb = (p, q, t) => {
                    if (t < 0) t += 1;
                    if (t > 1) t -= 1;
                    return t < 1/6 ? p + (q - p) * 6 * t :
                        t < 1/2 ? q :
                            t < 2/3 ? p + (q - p) * (2/3 - t) * 6 : p;
                };
                const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                const p = 2 * l - q;
                r = hue2rgb(p, q, h + 1/3);
                g = hue2rgb(p, q, h);
                b = hue2rgb(p, q, h - 1/3);
            }
            return [
                Math.round(r * 255),
                Math.round(g * 255),
                Math.round(b * 255)
            ];
        }

        // 动态颜色生成
        function getTimeColor() {
            const date = new Date();
            const totalMinutes = date.getHours() * 60 + date.getMinutes();
            return hslToRgb((totalMinutes * 0.25) % 360, 95, 50);
        }

        // 初始化画布
        function initCanvas() {
            // 移除旧画布
            const oldCanvas = document.getElementById('global-particle-canvas');
            if (oldCanvas) oldCanvas.remove();

            // 创建新画布
            canvas = document.createElement('canvas');
            canvas.id = 'global-particle-canvas';
            Object.assign(canvas.style, {
                position: 'fixed',
                top: '0',
                left: '0',
                zIndex: CONFIG.Z_INDEX,
                opacity: CONFIG.OPACITY,
                pointerEvents: 'none'
            });
            document.documentElement.appendChild(canvas);

            ctx = canvas.getContext('2d');
            updateSize();
        }

        // 更新画布尺寸
        function updateSize() {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
        }

        // 创建粒子
        function createParticles() {
            particles = Array.from({ length: CONFIG.PARTICLE_COUNT }, () => ({
                x: Math.random() * width,
                y: Math.random() * height,
                vx: (Math.random() - 0.5) * CONFIG.BASE_SPEED,
                vy: (Math.random() - 0.5) * CONFIG.BASE_SPEED,
                max: Math.pow(CONFIG.LINE_MAX_DISTANCE, 2)
            }));
        }

        // 动画循环
        function animate() {
            ctx.clearRect(0, 0, width, height);

            // 获取当前颜色
            const [r, g, b] = getTimeColor();
            const lineColor = `rgba(${r},${g},${b}`;
            const dotColor = `rgb(${r},${g},${b})`;

            // 绘制粒子
            particles.forEach(particle => {
                // 更新位置
                particle.x += particle.vx;
                particle.y += particle.vy;

                // 边界反弹
                if (particle.x < 0 || particle.x > width) particle.vx *= -1;
                if (particle.y < 0 || particle.y > height) particle.vy *= -1;

                // 绘制粒子点
                ctx.fillStyle = dotColor;
                ctx.fillRect(particle.x - 0.5, particle.y - 0.5, 1, 1);

                // 绘制连线
                particles.forEach(other => {
                    if (particle !== other) {
                        const dx = particle.x - other.x;
                        const dy = particle.y - other.y;
                        const distSq = dx*dx + dy*dy;

                        if (distSq < particle.max) {
                            ctx.beginPath();
                            ctx.strokeStyle = `${lineColor},${1 - distSq/particle.max}`;
                            ctx.lineWidth = 0.8;
                            ctx.moveTo(particle.x, particle.y);
                            ctx.lineTo(other.x, other.y);
                            ctx.stroke();
                        }
                    }
                });

                // 鼠标互动
                if (mouse.x !== null && mouse.y !== null) {
                    const dx = particle.x - mouse.x;
                    const dy = particle.y - mouse.y;
                    const distSq = dx*dx + dy*dy;

                    if (distSq < 10000) { // 100px半径
                        particle.x += dx * CONFIG.MOUSE_INFLUENCE * 0.1;
                        particle.y += dy * CONFIG.MOUSE_INFLUENCE * 0.1;
                    }
                }
            });

            animationFrameId = requestAnimationFrame(animate);
        }

        // 事件监听
        function initEvents() {
            // 防抖调整尺寸
            let resizeTimer;
            window.addEventListener('resize', () => {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(() => {
                    updateSize();
                    createParticles();
                }, 200);
            });

            // 鼠标追踪
            window.addEventListener('mousemove', e => {
                mouse.x = e.clientX;
                mouse.y = e.clientY;
            });

            window.addEventListener('mouseout', () => {
                mouse.x = null;
                mouse.y = null;
            });
        }

        // 初始化入口
        function init() {
            initCanvas();
            createParticles();
            initEvents();
            animate();
        }

        // 清理函数
        function cleanup() {
            cancelAnimationFrame(animationFrameId);
            canvas.remove();
            window.removeEventListener('resize', updateSize);
        }

        return { init, cleanup };
    })();

    // 执行初始化
    if (document.readyState === 'complete') {
        GLOBAL_PARTICLE_EFFECT.init();
    } else {
        window.addEventListener('load', GLOBAL_PARTICLE_EFFECT.init);
    }

    // 页面卸载时清理
    window.addEventListener('beforeunload', () => {
        GLOBAL_PARTICLE_EFFECT.cleanup();
    });
}